package com.android.powerbankpad;

import android.Manifest;

import com.android.powerbankpad.bean.AdBean;
import com.android.powerbankpad.bean.ChildBean;
import com.android.powerbankpad.config.Constants;
import com.ws.universal.tools.ContextInit;
import com.ws.universal.tools.bottomdialog.PopBottonDialog;
import com.ws.universal.tools.countdown.CommitTimer;
import com.ws.universal.tools.eventbus.BaseBusData;
import com.ws.universal.tools.eventbus.EventBusUtil;
import com.ws.universal.tools.network.JSONFormat;
import com.ws.universal.tools.utils.CacheUtils;
import com.ws.universal.tools.utils.GsonUtils;
import com.ws.universal.tools.utils.LogcatUtils;
import com.ws.universal.tools.utils.PermissionUtils;
import com.ws.universal.tools.utils.ShellUtils;
import com.ws.universal.tools.utils.TimeUtils;
import com.ws.universal.tools.utils.cache.CacheDoubleStaticUtils;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;

public class MainTools {


    private static MainTools mainTools;

    private PopBottonDialog selectImgDialog;// 生日选择
    private Timer timerLoadData; //根据时间点轮询加载广告数据
    private int screenOrientation;

    public static MainTools getInstance() {
        if (mainTools == null) {
            mainTools = new MainTools();
        }
        return mainTools;
    }

    public void checkPermissions() {

        LogcatUtils.d("   ShellUtils 是否 root: " + ShellUtils.is_root());

//        boolean changeWifiState = AndPermission.hasPermissions(mActivity, Manifest.permission.CHANGE_WIFI_STATE);
//        LogcatUtils.d("LogcatUtils   MainPresenter  权限检测 : " + changeWifiState);

        boolean accessWifiState = PermissionUtils.hasPermissions(ContextInit.getContext(), Manifest.permission.ACCESS_WIFI_STATE);

        boolean readExternalStorage = PermissionUtils.hasPermissions(ContextInit.getContext(), Manifest.permission.READ_EXTERNAL_STORAGE);
        boolean writeExternalStorage = PermissionUtils.hasPermissions(ContextInit.getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
        boolean accessCoarseLocation = PermissionUtils.hasPermissions(ContextInit.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION);
        boolean accessFineLocation = PermissionUtils.hasPermissions(ContextInit.getContext(), Manifest.permission.ACCESS_FINE_LOCATION);
        boolean readPhoneState = PermissionUtils.hasPermissions(ContextInit.getContext(), Manifest.permission.READ_PHONE_STATE);
        boolean systemAlertWindow = PermissionUtils.hasPermissions(ContextInit.getContext(), Manifest.permission.SYSTEM_ALERT_WINDOW);
        boolean installPackages = PermissionUtils.hasPermissions(ContextInit.getContext(), Manifest.permission.INSTALL_PACKAGES);
        boolean killBackgroundProcesses = PermissionUtils.hasPermissions(ContextInit.getContext(), Manifest.permission.KILL_BACKGROUND_PROCESSES);
        boolean usbPermissions = PermissionUtils.hasPermissions(ContextInit.getContext(), "com.pax.poslink.USB_PERMISSION");
        boolean isReceive_boot_completed = PermissionUtils.hasPermissions(ContextInit.getContext(), Manifest.permission.RECEIVE_BOOT_COMPLETED);
        boolean isWrite_settings = PermissionUtils.hasPermissions(ContextInit.getContext(), Manifest.permission.WRITE_SETTINGS);
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!accessWifiState) {
                    ShellUtils.CommandResult result = ShellUtils.execCmd(Constants.PM_GRANT + Manifest.permission.ACCESS_WIFI_STATE);
                    LogcatUtils.d("     ShellUtils 执行获取权限  ACCESS_WIFI_STATE: " + result.toString());
                }

                if (!readExternalStorage) {
                    ShellUtils.CommandResult result = ShellUtils.execCmd(Constants.PM_GRANT + Manifest.permission.READ_EXTERNAL_STORAGE);
                    LogcatUtils.d("      ShellUtils 执行获取权限  READ_EXTERNAL_STORAGE: " + result.toString());
                }
                if (!writeExternalStorage) {
                    ShellUtils.CommandResult result = ShellUtils.execCmd(Constants.PM_GRANT + Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    LogcatUtils.d("     ShellUtils 执行获取权限  WRITE_EXTERNAL_STORAGE: " + result.toString());
                }

                if (!accessCoarseLocation) {
                    ShellUtils.CommandResult result = ShellUtils.execCmd(Constants.PM_GRANT + Manifest.permission.ACCESS_COARSE_LOCATION);
                    LogcatUtils.d("      ShellUtils 执行获取权限  ACCESS_COARSE_LOCATION: " + result.toString());
                }
                if (!accessFineLocation) {
                    ShellUtils.CommandResult result = ShellUtils.execCmd(Constants.PM_GRANT + Manifest.permission.ACCESS_FINE_LOCATION);
                    LogcatUtils.d("      ShellUtils 执行获取权限  ACCESS_FINE_LOCATION: " + result.toString());
                }

                if (!isReceive_boot_completed) {
                    ShellUtils.CommandResult result = ShellUtils.execCmd(Constants.PM_GRANT + Manifest.permission.RECEIVE_BOOT_COMPLETED);
                    LogcatUtils.d("     ShellUtils 执行获取权限 if RECEIVE_BOOT_COMPLETED  : " + result.toString());
                } else {
                    LogcatUtils.d("     ShellUtils 执行获取权限 else  RECEIVE_BOOT_COMPLETED  : " + isReceive_boot_completed);
                }

             /*   if (!isWrite_settings) {
                    ShellUtils.CommandResult result = ShellUtils.execCmd(Constants.PM_GRANT + Manifest.permission.WRITE_SETTINGS);
                    LogcatUtils.d("     ShellUtils 执行获取权限  usb权限 : " + result.toString());
                }*/


                if (!readPhoneState) {
                    ShellUtils.CommandResult result = ShellUtils.execCmd(Constants.PM_GRANT + Manifest.permission.READ_PHONE_STATE);
                    LogcatUtils.d("     ShellUtils 执行获取权限  READ_PHONE_STATE: " + result.toString());
                }
                if (!systemAlertWindow) {
                    ShellUtils.CommandResult result = ShellUtils.execCmd("appops set com.android.powerbankpad SYSTEM_ALERT_WINDOW allow");
                    LogcatUtils.d("     ShellUtils 执行获取权限 SYSTEM_ALERT_WINDOW : " + result.toString());
                }
                if (!installPackages) {
                    ShellUtils.CommandResult result = ShellUtils.execCmd("appops set com.android.powerbankpad INSTALL_PACKAGES allow");
                    LogcatUtils.d("     ShellUtils 执行获取权限  INSTALL_PACKAGES: " + result.toString());
                }
                if (!killBackgroundProcesses) {
//                                ShellUtils.CommandResult result = ShellUtils.execCmd(ConstantDatas.PM_GRANT + Manifest.permission.KILL_BACKGROUND_PROCESSES, true);
                    ShellUtils.CommandResult result = ShellUtils.execCmd("appops set com.android.powerbankpad KILL_BACKGROUND_PROCESSES allow");
                    LogcatUtils.d("     ShellUtils 执行获取权限  KILL_BACKGROUND_PROCESSES: " + result.toString());
                }
                if (!usbPermissions) {
                    ShellUtils.CommandResult result = ShellUtils.execCmd("appops set com.android.powerbankpad com.pax.poslink.USB_PERMISSION allow");
                    LogcatUtils.d("     ShellUtils 执行获取权限  usb权限 : " + result.toString());
                }


                //隐藏虚拟键及顶部状态栏
                ShellUtils.CommandResult result = ShellUtils.execCmd("appops set com.android.powerbankpad READ_SMS allow");
                LogcatUtils.d("     ShellUtils 执行获取权限  appops: " + result.toString());
                ShellUtils.execCmd("settings put global policy_control immersive.full=*");


                BaseBusData beautyDate = new BaseBusData(Constants.execute_permissions);
                EventBusUtil.postEvent(beautyDate);

            }
        }).start();

    }

    public String shellGetMacAddress() {
        ShellUtils.CommandResult result = ShellUtils.execCmd("cat /sys/class/net/wlan0/address");
        String macAddress = result.successMsg;
        LogcatUtils.d("LogcatUtils   MainPresenter  ShellUtils 执行获取macAddress : " + macAddress);
        CacheUtils.setString(Constants.mac_address, macAddress);
//        MmkvUtils.getInstance().encode(ConstantDatas.MMKV_MAC_ADDRESS, "e4:08:e7:6b:bb:e4");
        return macAddress;
    }

    public void setScreenOrientation(int screenOrientation) {
        this.screenOrientation = screenOrientation;
    }

    private int current = 0;

    public void pollingLoadAd(AdBean adBean) {
        LogcatUtils.e("MainTools  MainActivity initPlayAd() 广告初始化 ");
        current = 0;
        if (timerLoadData != null) {
            timerLoadData.purge();
            timerLoadData.cancel();
            timerLoadData = null;
        }
        if (timerLoadData == null) {
            timerLoadData = new Timer();
        }
        timerLoadData.schedule(new CommitTimer() {
            @Override
            public void run() {

                for (int i = 0; i < adBean.list.size(); i++) {
                    boolean isWithin = TimeUtils.nowIsWithin(adBean.list.get(i).start, adBean.list.get(i).end);
                    if (isWithin) {
                        current = i;
                        try {
                            JSONArray jsonObject = new JSONArray(adBean.list.get(i).list.toString());
                            //LogcatUtils.e(" 发送广告数据 时间段 current " + current + "  loadAdDate " + JSONFormat.format(jsonObject.toString()));
                            BaseBusData beautyDate = new BaseBusData(Constants.loadAdDate, jsonObject.toString());
                            EventBusUtil.postEvent(beautyDate);
                        } catch (JSONException e) {
                            LogcatUtils.e(" 发送广告数据 JSONException " + e.toString() + " msg " + e.getMessage());
                        }
                        return;
                    } else {
                        boolean satisfy = TimeUtils.nowIsWithin(adBean.list.get(current).start, adBean.list.get(current).end);
                        LogcatUtils.e(" 发送广告数据 默认  i " + i + " 是否满足 " + isWithin + " " + adBean.list.get(i).start + " " + adBean.list.get(i).end);
                        LogcatUtils.e(" 发送广告数据 默认  current " + current + " 是否满足 " + satisfy + " " + adBean.list.get(current).start + " " + adBean.list.get(current).end);
                        if (!satisfy) {
                            playDefaultImage(adBean);
                        }


                    }
                }


            }
        }, 0, 10 * 1000);////Teask，延时时间，轮询间隔

    }

    public void playDefaultImage(AdBean adBean) {
        ChildBean childBean = null;
        List<ChildBean> beanList = null;
        if (screenOrientation == 1) { //竖屏
            childBean = new ChildBean("image", "0", adBean.default_vertical);
            beanList = new ArrayList<>();
            beanList.add(childBean);
        } else { //横屏
            childBean = new ChildBean("image", "0", adBean.default_cross);
            beanList = new ArrayList<>();
            beanList.add(childBean);
        }
        try {
            JSONArray jsonObject = new JSONArray(beanList.toString());
            BaseBusData beautyDate = new BaseBusData(Constants.loadAdDate, jsonObject.toString());
            EventBusUtil.postEvent(beautyDate);
        } catch (JSONException e) {

        }
    }


    public void onDesTroy() {
        if (timerLoadData != null) {
            timerLoadData.purge();
            timerLoadData.cancel();
            timerLoadData = null;
        }
    }


}
